/*
 * @(#)SerializationUtil.java 创建于 2015-12-10 14:57:32
 *
 * 版权：版权所有 Bsoft 保留所有权力。
 */
package hcn.sync.util;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.HessianFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author <a href="mailto:chinnsii@163.com">zhengshi</a>
 */
public class SerializationUtil {

    private final static HessianFactory hessianFactory = new HessianFactory();

    /**
     * @param object
     * @return
     * @throws IOException
     */
    public static byte[] serialize(Object object) throws IOException {
        if (object == null) {
            return null;
        }
        ByteArrayOutputStream outs = new ByteArrayOutputStream();
        Hessian2Output h2out = hessianFactory.createHessian2Output(outs);

//        h2out.startReply();
        h2out.writeObject(object);
//        h2out.completeReply();
        h2out.flush();
        return outs.toByteArray();
    }

    /**
     * @param bytes
     * @return
     * @throws IOException
     */
    public static <T> T deserialize(byte[] bytes) throws IOException {
        if (bytes == null) {
            return null;
        }
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        Hessian2Input h2In = hessianFactory.createHessian2Input(in);
        //noinspection unchecked
        return (T) h2In.readObject();
    }

    /**
     *
     * @param bytes
     * @param tClass
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T deserialize(byte[] bytes, Class<T> tClass) throws IOException {
        Object object = deserialize(bytes);
        if (object == null) {
            return null;
        }
        if (!tClass.isAssignableFrom(object.getClass())) {
            throw new ClassCastException("Instance of class " + object.getClass() + " cannot cast to " + tClass);
        }
        //noinspection unchecked
        return (T) object;
    }
}
